package com.primes.util;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * class to store and retrieve objects from various places.
 * @author hard
 *
 */
public class ObjectIO {
	static final String output_dir = "files"+File.separator;
	static {
		try {
			File dir = new File(output_dir);
			if (!dir.exists())
				dir.mkdirs();
		} catch (Exception e) {
		}
	}

	
	public static void write(Object f, Class className) throws Exception{
        XMLEncoder encoder =
           new XMLEncoder(
              new BufferedOutputStream(
                new FileOutputStream(output_dir+className.getName()+".xml")));
        encoder.writeObject(f);
        encoder.close();
    }

    public static Object read(Class className) throws Exception {
        XMLDecoder decoder =
            new XMLDecoder(new BufferedInputStream(
                new FileInputStream(output_dir+className.getName()+".xml")));
        Object o = (Object)decoder.readObject();
        System.out.println(o.getClass().getName());
        decoder.close();
        return o;
    }
	
	

}
